<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>维修工工作台 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/all.min.css}" rel="stylesheet">
    <script th:src="@{/js/jquery.min.js}"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=spEZ8x14LoDN10ejoQD7GdxOEJYOwqcw"></script>
    <style>
        #map {
            height: 500px;
            width: 100%;
        }
        .order-list {
            max-height: 600px;
            overflow-y: auto;
        }
        .order-card {
            cursor: pointer;
        }
        .order-card:hover {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">维修工工作台</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">工作台</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/repairman/orders">我的订单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/repairman/profile">个人资料</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/repairman-announcements">公告</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3" id="userInfo"></span>
                    <button class="btn btn-outline-light" onclick="logout()">退出</button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 公告组件 -->
    <div th:replace="common/announcement :: announcement_bell"></div>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">工作地图</h5>
                    </div>
                    <div class="card-body">
                        <div id="map"></div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">工作状态</h5>
                    </div>
                    <div class="card-body">
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" id="workStatus" checked>
                            <label class="form-check-label" for="workStatus">在线接单</label>
                        </div>
                        <div class="alert alert-info">
                            当前位置：<span id="currentLocation">正在获取...</span>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">待接单列表</h5>
                    </div>
                    <div class="card-body order-list">
                        <div id="orderList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 公告组件脚本 -->
    <div th:replace="common/announcement :: announcement_script"></div>
    <script>
        let map;
        let currentUser = null;
        let currentOrder = null;
        let geolocation = null;
        let locationMarker = null;

        // 初始化地图
        function initMap() {
            map = new BMap.Map("map");
            const point = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(point, 12);
            map.enableScrollWheelZoom(true);

            // 初始化定位
            geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function(r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    const point = new BMap.Point(r.point.lng, r.point.lat);
                    map.centerAndZoom(point, 15);

                    // 更新位置标记
                    if (locationMarker) {
                        map.removeOverlay(locationMarker);
                    }
                    locationMarker = new BMap.Marker(point);
                    map.addOverlay(locationMarker);

                    // 更新当前位置显示
                    const geocoder = new BMap.Geocoder();
                    geocoder.getLocation(point, function(rs) {
                        $('#currentLocation').text(rs.address);
                    });

                    // 更新位置到服务器
                    updateLocation(r.point.lat, r.point.lng);
                }
            });
        }

        // 更新位置到服务器
        function updateLocation(lat, lng) {
            $.ajax({
                url: '/api/order/repairman/location',
                type: 'PUT',
                contentType: 'application/json',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                data: JSON.stringify({
                    repairmanId: currentUser.id,
                    latitude: lat,
                    longitude: lng
                })
            });
        }

        // 获取用户信息
        function getUserInfo() {
            $.ajax({
                url: '/api/user/profile',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                success: function(response) {
                    currentUser = response;
                    $('#userInfo').text('欢迎，' + response.realName);
                    loadOrders();
                },
                error: function() {
                    window.location.href = '/login';
                }
            });
        }

        // 加载订单列表
        function loadOrders() {
            $.ajax({
                url: '/api/repairman/orders',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                data: {
                    status: '0'  // 待接单状态
                },
                success: function(orders) {
                    const orderList = $('#orderList');
                    orderList.empty();
                    orders.forEach(order => {
                        orderList.append(`
                            <div class="card mb-2 order-card" onclick="showOrderDetail(${order.id})">
                                <div class="card-body">
                                    <h6 class="card-title">${order.appliance_type}</h6>
                                    <p class="card-text">地址：${order.address}</p>
                                    <p class="card-text">预约时间：${new Date(order.appointment_time).toLocaleString()}</p>
                                </div>
                            </div>
                        `);
                    });
                }
            });
        }

        // 显示订单详情
        function showOrderDetail(orderId) {
            if (currentOrder) {
                return;
            }

            $.ajax({
                url: '/api/order/' + orderId,
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                success: function(order) {
                    currentOrder = order;

                    // 在地图上显示订单位置
                    const point = new BMap.Point(order.longitude, order.latitude);
                    const marker = new BMap.Marker(point);
                    map.addOverlay(marker);

                    // 显示订单详情对话框
                    const dialog = $(`
                        <div class="modal fade" id="orderDetailModal" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">订单详情</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <p><strong>家电类型：</strong>${order.appliance_type}</p>
                                        <p><strong>故障描述：</strong>${order.description}</p>
                                        <p><strong>维修地址：</strong>${order.address}</p>
                                        <p><strong>预约时间：</strong>${new Date(order.appointment_time).toLocaleString()}</p>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                        <button type="button" class="btn btn-primary" onclick="acceptOrder(${order.id})">接单</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);
                    dialog.modal('show');
                }
            });
        }

        // 接单
        function acceptOrder(orderId) {
            $.ajax({
                url: '/api/order/' + orderId + '/accept',
                type: 'POST',
                contentType: 'application/json',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token')
                },
                data: JSON.stringify({
                    repairmanId: currentUser.id
                }),
                success: function() {
                    alert('接单成功！');
                    $('#orderDetailModal').modal('hide');
                    currentOrder = null;
                    loadOrders();
                },
                error: function(xhr) {
                    alert('接单失败：' + xhr.responseText);
                }
            });
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }

        // 页面加载完成后初始化
        $(document).ready(function() {
            initMap();
            getUserInfo();

            // 定时更新位置
            setInterval(function() {
                if (geolocation) {
                    geolocation.getCurrentPosition(function(r) {
                        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                            const point = new BMap.Point(r.point.lng, r.point.lat);
                            if (locationMarker) {
                                map.removeOverlay(locationMarker);
                            }
                            locationMarker = new BMap.Marker(point);
                            map.addOverlay(locationMarker);
                            updateLocation(r.point.lat, r.point.lng);
                        }
                    });
                }
            }, 30000); // 每30秒更新一次位置
        });
    </script>
</body>
</html> 